package de.uni_mannheim.informatik.ai.dame_ai.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XmlFileAccess extends FileAccess	{
	
	private static final String XML_HEADER="<?xml version=\"1.0\" encoding='UTF-8'?>";
	private static final Pattern lastTagPat= Pattern.compile("(</.+?>)");
	
	
	/**
	 * This method inserts content into a Xml file.</br>
	 * content will become the last child / children of the root element in dest.</br>
	 * content of course has to consist of properly nested XML.</br>
	 * @param dest destination file
	 * @param content xml content to insert into dest
	 * @throws IOException Thrown if dest cannot be accessed.
	 */
	public boolean insertXml(File dest, String content){
		String fileCont=readFile(dest);
		int insertLoc=getInsertLocation(fileCont);
		String partBefore=fileCont.substring(0, insertLoc);
		String partAfter=fileCont.substring(insertLoc, fileCont.length());
		String result=partBefore + content + LINE_SEP + partAfter + LINE_SEP;
		return write(result, dest);
	}
	
	/**
	 * Append Xml header to content and write content into the File specified by dest.</br>
	 * <b>ATTENTION:</b> If dest already exists in the file system, it will
	 * be overwritten without request.
	 */
	public boolean writeXml(String content, File dest){
		//temporary hack
		String contWithHeader = XML_HEADER + LINE_SEP + content;
		return write(contWithHeader, dest);
	}
	
	
	/**
	 * Write content into the File specified by dest.</br>
	 * <b>ATTENTION:</b> If dest already exists in the file system, it will
	 * be overwritten without request.
	 */
	private boolean write(String content, File dest){
		//int hashValue=getHashValue(content);
		try {
			FileWriter fileWriter = new FileWriter(dest);
			fileWriter.write(content);
			fileWriter.flush();
			fileWriter.close();
		} catch (IOException e) {
				e.printStackTrace();
				return false;
		}
		return true;
	}
	
	/**
	 * Returns the index of the first char of xml's end tag.</br>
	 */
	private int getInsertLocation(String xml){
		Matcher matchEndTag = lastTagPat.matcher(xml);
		matchEndTag.find();
		int insertLoc=0;
		while(matchEndTag.find())
			insertLoc=matchEndTag.start();
		return insertLoc;
	}
	
	/**
	 * Copies the content of src to dest.
	 * @param src src file that should be copied
	 * @param dest file into which the content of src should be copied
	 * @return true if operation was successful, else false.
	 */
	public boolean copy(File src, File dest){
		boolean success=false;
		if(src.exists())	{
			String fileContent = readFile(src);
			success = write(fileContent, dest);
		}
		return success;
	}
	
//	private int getHashValue(String text){
//		int hashValue=0;
//		for(int i=0; i<text.length(); i++){
//			char c=text.charAt(i);
//			hashValue+=c*(i+17);
//		}
//		return hashValue;
//	}
}